<template>
	<view>
		<u-navbar :title="navtitle" :bgColor="bg" :placeholder="false" leftIconColor="#fff">
		</u-navbar>
		<!-- 轮播图 -->
		<view class="swiperBox">
			<u-swiper :autoplay="false" :current="current" :list="swiperlist" interval="5000" :height="swiperh"
				indicator radius="0" @change="(e) => (current = e.current)" :videoMask="false">
				<view slot="indicator" class="indicator">
					<view class="indicator__dot" v-for="(item, index) in swiperlist" :key="index"
						:class="[index === current && 'indicator__dot--active']">
					</view>
				</view>
			</u-swiper>
		</view>
		<u-notice-bar v-if="browse" :step="true" direction="column" :text="browsetext"></u-notice-bar>
		<u-notice-bar v-if="query.type == 'share' && share < 3" :step="true" direction="column"
			:text="sharetext"></u-notice-bar>
		<!-- 价格与标题 -->
		<view class="price_title">
			<!-- 价格 -->
			<view class="priceBox">
				<view class="price" v-if="data.unitPrice && data.unitPrice != 0">
					<text>￥</text>
					<!-- <text>{{ data.retentionMoney }}</text> -->
					<text class="priceMin">{{ data.unitPrice || 0 }}</text>
					<text class="unit" v-if="data.unit&&data.unit!='null'">{{ data.unit }}</text>
				</view>
				<!-- {{ labels }} -->
				<view class="label">
					<text v-for="(litem, lindex) in labels" :key="lindex"
						:style="{ backgroundColor: litem.attrs.bgColor }">{{ litem.text }}</text>
				</view>
				<view class="like" @click="favoritefn()">
					<image src="/static/goodsitem/product_unfavor.png" v-if="!favorite"></image>
					<image src="/static/goodsitem/product_favor.png" v-else></image>
					<view class="u-flex">
						<text class="totaltext" v-if="total != 0">{{ total }}人收藏</text>
						<text class="sctext" v-else>{{
              favorite ? "收藏" : "未收藏"
            }}</text>
					</view>
				</view>
			</view>
			<!-- 标题区 -->
			<view class="goodsTitle">
				<view class="main">{{ data.productName }}</view>
				<view v-if="data.pastureLevel && data.pastureLevel != 0">
					<u-rate count="5" v-model="data.pastureLevel" readonly></u-rate>
				</view>
				<view class="sub">
					<!-- <view class="">
						{{ levelType }}
					</view> -->
					<view class="retentionMoney" v-if="data.retentionMoney">
						质量保证金<text class="text">{{ data.retentionMoney }}</text>
					</view>
				</view>

				<view class="activity" v-if="data.userRemarks">
					{{ data.userRemarks }}
				</view>
			</view>
		</view>
		<view class="function">
			<u-cell-group>
				<u-cell title="发布时间" :value="$u.timeFormat(data.createTime, 'yyyy-mm-dd')">

				</u-cell>
				<u-cell title="货源位置" :label="data.sourceLocation" @click="openLocationfn">
					<template #value>
						<view class="mapicon">
							<view class="iconbox">
								<view class="icon">
									<u-icon name="map-fill" color="#333" size="12"></u-icon>
								</view>
								<view class="text"> 地图 </view>
							</view>
						</view>
					</template>
				</u-cell>
				<template v-for="(item, index) in inputs">
					<template v-if="item.type == 'selectProps'">
						<!-- label -->
						<u-cell v-if="inputstr(item2, formdata[item.value])" v-for="(item2, index2) in item.inputs"
							:title="item2.label" :value="inputstr(item2, formdata[item.value])">
						</u-cell>
					</template>
					<u-cell v-else-if="inputstr(item, formdata)" :title="item.label" :value="inputstr(item, formdata)">
					</u-cell>
				</template>
				<u-cell title="质量报告" v-if="data.reportFile && data.reportFile.length != 0">
					<template #value>
						<view class="reportFile">
							<view class="" v-for="(item, index) in data.reportFile"
								style="margin-right: 10rpx; margin-bottom: 10rpx" :key="index">
								<u-tag :text="`报告${index + 1}`" size="mini" type="primary"
									@click="reportFiletap(item)"></u-tag>
							</view>
						</view>
					</template>
				</u-cell>
			</u-cell-group>
		</view>
		<view style="height: 180rpx"></view>
		<!-- 底部菜单 -->
		<view class="bottom-menu">
			<view class="btns">
				<view class="btn" @click="goindex">
					<u-icon name="home" custom-prefix="custom-icon" size="18"></u-icon>
					<text>首页</text>
				</view>
			</view>
			<view class="next">
				<view :class="{one:!(data.contactPhone || data.companyPhone)}" @click="sharefn()">分享
					<button open-type="share" class="btn" v-if="islogin">分享</button>
				</view>
				<view @click="call" v-if="data.contactPhone || data.companyPhone">立即联系</view>
			</view>
		</view>
		<u-action-sheet :actions="Phonelist" :show="Phoneshow" cancelText="取消" @select="Phoneselect"
			@close="Phoneshow = false"></u-action-sheet>
	</view>
</template>

<script>
	import {
		getReleaseInfo
	} from "@/api/release.js";
	import {
		getDicts
	} from "@/api/dictdata";
	import {
		getProductClassAll
	} from "@/api/index.js";
	import {
		getClassBindingFormsByBindingId
	} from "@/api/release";
	import {
		getMember,
		join,
		cancelMember,
		getTotal
	} from "@/api/favorite";
	import {
		getAccessToken,
		removeToken
	} from "@/utils/auth";
	import {
		getUser
	} from "@/api/user.js";

	import {
		stacking
	} from "@/api/points.js";
	import {
		pointsRemainTimes
	} from "@/api/points.js";
	export default {
		name: "tabbar",
		data() {
			return {
				swiperh: "750rpx",
				current: 0,
				Phonelist: [],
				Phoneshow: false,
				query: {},
				total: 0,
				data: {},
				navtitle: "",
				bg: "transparent",
				dicts: {},
				dicts: {},
				levelTypeList: [],
				favorite: false,
				levelType: "",
				inputs: [],
				formdata: {},
				//   是否登陆
				islogin: false,
				// 用户信息
				user: {},
				share: 0,
				sharetext: ["分享商品获得积分"],
			};
		},
		onLoad(query) {
			this.query = query;
			this.init();
			this.$store.commit("index/setProductId", this.query.id);
		},
		beforeDestroy() {
			this.$store.commit("index/setProductId", "");
		},
		onShow() {
			this.usrinit();
		},
		computed: {
			browse() {
				return this.$store.state.index.browse;
			},
			browsetext() {
				return this.$store.state.index.browsetext;
			},
			swiperlist() {
				try {
					let r = this.data.imagesUrl.split(",");
					if (this.data.videoUrl) {
						r.push(this.data.videoUrl);
					}
					return r;
				} catch (error) {
					return [];
				}
			},
			labels() {
				let r = [];
				try {
					let dqtransactionalMode = this.dicts["transactional_mode"].find(
						(item) => {
							return item.value == this.data.transactionalMode;
						}
					);
					if (dqtransactionalMode) {
						r.push({
							text: dqtransactionalMode.label,
							attrs: {
								bgColor: "#F3B367",
							},
						});
					}
					// manage_model
					let dqmanage_model = this.dicts["manage_model"].find((item) => {
						return item.value == this.data.manageModel;
					});

					if (dqmanage_model) {
						r.push({
							text: dqmanage_model.label,
							attrs: {
								bgColor: "#DC6A71",
							},
						});
					}
					if (this.data.discount == 1) {
						r.push({
							text: "特惠",
							attrs: {
								bgColor: "#39C03E",
							},
						});
					}
				} catch (error) {}
				return r;
			},
		},
		onShareAppMessage: function() {
			// swiperh: "750rpx",
			this.swiperh = "400rpx";
			setTimeout(() => {
				this.swiperh = "750rpx";
			}, 300);
			let data = {
				url: "/pages/shop/goods/detail/detail",
				query: this.query,
				type: "share",
			};
			if (this.islogin && this.query.type == "share" && this.share < 3) {
				//   this.share++;&& this.share <= 3
				stacking({
					bizType: 2,
					productId: this.query.id
				});
			}
			return {
				title: this.data.productName, // 动态标题
				path: "/pages/index/index?type=share&data=" + JSON.stringify(data), // 动态路径
				// imageUrl: this.swiperlist.length == 0 ? '' : this.swiperlist[0],
			};
		},
		// 右上角转发到朋友圈
		onShareTimeline() {
			this.swiperh = "400rpx";
			setTimeout(() => {
				this.swiperh = "750rpx";
			}, 300);
			if (this.islogin && this.query.type == "share" && this.share < 3) {
				// 
				//   this.share++;
				stacking({
					bizType: 2,
					productId: this.query.id
				});
			}
			return {
				title: this.data.productName, // 动态标题
				query: "id=" + this.query.id,
				// imageUrl: this.swiperlist.length == 0 ? '' : this.swiperlist[0],
			};
		},
		methods: {
			async init() {
				// route: "pages/shop/goods/list/list"
				const res = await getProductClassAll();
				this.levelTypeList = res.data;

				let {
					data
				} = await getDicts("transactional_mode,manage_model");

				let transactional_mode = data.filter((e) => {
					return e.dictType == "transactional_mode";
				});
				let manage_model = data.filter((e) => {
					return e.dictType == "manage_model";
				});

				this.dicts = {
					transactional_mode,
					manage_model,
				};
				let ReleaseInfo = await getReleaseInfo(this.query);

				this.data = ReleaseInfo.data;
				this.data.reportFile = (this.data.reportFile || "")
					.split(",")
					.filter((e) => e);
				console.log(this.data.reportFile.length, "this.data.reportFile");
				// this.navtitle = this.data.productName;
				this.levelTypestr();
				this.getInputs(this.data.level3Type);
				//   s收藏
			},
			reportFiletap(item) {
				console.log(item);
				if (uni.$u.test.image(item)) {
					uni.previewImage({
						// 先filter找出为图片的item，再返回filter结果中的图片url
						urls: [item],
						current: item,
						fail() {
							uni.$u.toast("预览图片失败");
						},
					});
					return;
				}
				uni.navigateTo({
					url: "/pages/webView/webView?file=" + item,
				});
				// uni.setClipboardData({
				// 	data: item,
				// 	success: function() {
				// 		uni.$u.toast('链接已复制到剪切板，请到浏览器中查看')
				// 	}
				// });
			},
			async usrinit() {
				if (getAccessToken()) {
					try {
						let data = await getUser();
						if (data?.data) {
							this.user = data.data;
							this.islogin = true;
						} else {
							removeToken();
						}
					} catch {
						removeToken();
					}
				} else {
					removeToken();
					this.islogin = false;
					this.user = {};
				}
				if (this.islogin) {
					let favorite = await getMember({
						id: this.query.id,
					});
					this.favorite = favorite.data == 0 ? true : false;
				}
				let total = await getTotal({
					productId: this.query.id,
				});
				this.total = total.data;
				if (this.query.type == "share") {
					let browseShare = await pointsRemainTimes();
					browseShare = browseShare.data;

					this.share = Number(browseShare.share) || 0;
				}
			},
			async sharefn(id) {
				if (!this.islogin) {
					uni.navigateTo({
						url: "/pages/login/login",
					});
					return;
				}
			},
			async favoritefn() {
				if (!this.islogin) {
					uni.navigateTo({
						url: "/pages/login/login",
					});
					return;
				}
				if (this.favorite) {
					await cancelMember({
						id: this.query.id,
						// userId: this.user.id,
					});
				} else {
					await join({
						userId: this.user.id,
						productTradingId: this.query.id,
					});
				}
				await this.usrinit();
			},
			call() {
				if (!this.islogin) {
					uni.navigateTo({
						url: "/pages/login/login",
					});
					return;
				}
				if (!this.data.contactPhone && !this.data.companyPhone) {
					this.$u.toast("暂无联系方式")
					return
				}
				if (this.data.companyPhone && this.data.platformTrading == 0) {
					uni.makePhoneCall({
						phoneNumber: this.data.companyPhone,
					});


					return
				} else if (this.data.contactPhone && this.data.platformTrading == 1) {
					uni.showModal({
						title: '提示',
						content: '该数据并未通过平台进行交易验证,建议您谨慎使用!',
						confirmText: "拨打",
						success: (res) => {
							if (res.confirm) {
								uni.makePhoneCall({
									phoneNumber: this.data.contactPhone,
								});
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
					return
				}

				if (this.data.contactPhone && this.data.companyPhone) {
					this.Phonelist = [{
							phone: this.data.contactPhone,
							name: "个人电话",
						},
						{
							phone: this.data.companyPhone,
							name: "公司电话",
						},
					];
					this.Phoneshow = true;
					return;
				}
				uni.makePhoneCall({
					phoneNumber: this.data.contactPhone || this.data.companyPhone,
				});
			},
			Phoneselect(item) {
				uni.makePhoneCall({
					phoneNumber: item.phone,
				});
				// this.Phoneshow = false;
			},
			levelTypestr() {
				let level1Type = this.levelTypeList.find((item) => {
					return item.id == this.data.level1Type;
				});
				level1Type = level1Type ? level1Type.fullName : "";
				let level2Type = this.levelTypeList.find((item) => {
					return item.id == this.data.level2Type;
				});
				level2Type = level2Type ? level2Type.fullName : "";
				let level3Type = this.levelTypeList.find((item) => {
					return item.id == this.data.level3Type;
				});
				level3Type = level3Type ? level3Type.fullName : "";
				this.levelType = `${level1Type} ${level2Type} ${level3Type}`;
			},
			inputstr(item, data) {
				// "select"
				if (item.type == "select") {
					if (item?.props?.multiple) {
						let str = data[item.value] || [];
						let options = item.options || [];
						let dqOption = options.filter((e) => {
							return str.includes(e.value);
						});
						if (dqOption.length != 0) {
							return dqOption.map((e) => e.label).join();
						}
					}

					let options = item.options || [];
					let dqOption = options.find((e) => {
						return e.value == data[item.value];
					});
					if (dqOption) {
						return dqOption.label;
					}
				}
				return data[item.value];
			},
			async getInputs(level3Type) {
				let data = JSON.parse(this.data.jsonForms);
				this.formdata = data;
				let reqData = await getClassBindingFormsByBindingId({
					bindingId: level3Type,
				});
				reqData = reqData.data;
				let rule, option;
				if (reqData && reqData.formsJson) {
					let remarks = JSON.parse(reqData.formsJson);
					rule = JSON.parse(`${remarks.rule.replaceAll("\\", "\\\\")}`);
					option = JSON.parse(`${remarks.options.replaceAll("\\", "\\\\")}`);
				} else {
					rule = [];
					option = {};
				}

				this.inputs = rule.map((e) => {
					if (e.type == "selectProps") {
						try {
							let keys = Object.keys(this.formdata[e.field]);

							e.inputs = e.props.options.filter((e2) => {
								return keys.includes(e2.value);
							});
						} catch (error) {
							e.inputs = [];
						}
					}
					return {
						...e,
						label: e.title,
						value: e.field,
					};
				});
			},
			goindex() {
				uni.redirectTo({
					url: "/pages/index/index",
				});
			},
			openLocationfn() {
				let lnglat = (this.data.coordinate || "").split(",");
				if (lnglat.length == 2) {
					uni.openLocation({
						latitude: Number(lnglat[1]),
						longitude: Number(lnglat[0]),
						scale: 18,
						success: function() {
							console.log("success");
						},
					});
				} else {
					this.$u.toast("暂无位置");
				}
			},
		},
	};
</script>
<style lang="scss" scoped>
	.indicator {
		@include flex(row);
		justify-content: center;

		&__dot {
			height: 6px;
			width: 6px;
			border-radius: 100px;
			background-color: rgba(255, 255, 255, 0.35);
			margin: 0 5px;
			transition: background-color 0.3s;

			&--active {
				background-color: #ffffff;
			}
		}
	}

	.function {
		position: relative;
		background: #fff;
		margin-top: 20rpx;

		u-icon {
			color: #c5c5c5 !important;
			transform: translateX(10rpx) !important;
		}
	}

	.slot-wrap {
		position: relative;
		margin-left: 20rpx;
		width: 60rpx;
		height: 60rpx;
		border-radius: 30rpx;
		color: #fff;
		background-color: rgba($color: #000000, $alpha: 0.2);
		border: 2rpx solid rgba($color: #ffffff, $alpha: 0.2);

		.slot-icon {
			justify-content: center;
			width: 50%;
			height: inherit;
		}

		.gap {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			width: 2rpx;
			height: 36rpx;
			background-color: rgba($color: #f1f1f1, $alpha: 0.2);
		}
	}

	.price_title {
		background-color: #ffffff;
		padding: 20rpx 24rpx 16rpx;
	}

	.priceBox {
		display: flex;
		margin-bottom: 16rpx;
		font-family: "JDBold";

		.price {
			color: #d51010;
			font-weight: bold;
			font-size: 30rpx;

			text:nth-child(2) {
				font-size: 42rpx;
			}

			.unit {
				font-size: 24rpx;
				color: #999;
			}
		}

		.market_price {
			display: inline-block;
			margin: 18rpx 20rpx 0;
			font-size: 24rpx;
			color: #888;
			font-family: "JDNormal";
			text-decoration: line-through;
		}

		.label {
			display: inline-block;
			margin-top: 18rpx;
			margin-left: 10rpx;
			padding: 0 8rpx;
			height: 32rpx;
			line-height: 32rpx;
			font-size: 22rpx;
			border-radius: 8rpx;
			color: #fff;

			text {
				display: inline-block;
				border-radius: 4rpx;
				// background-color: #d96b6c;
				color: #ffffff;
				margin-right: 10rpx;
				text-align: center;
				height: 32rpx;
				padding: 0 10rpx;
				line-height: 32rpx;
				font-size: 24rpx;
			}
		}

		.like {
			margin-left: auto;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;

			image {
				height: 40rpx;
				width: 40rpx;
			}

			.sctext {
				font-size: 24rpx;
				color: #999;
				line-height: 1.3;
			}

			.totaltext {
				font-size: 24rpx;
				color: $uni-color-error;
				line-height: 1.3;
			}
		}
	}

	.goodsTitle {
		.main {
			font-size: 30rpx;
			font-weight: bold;
			color: #333;
		}

		.sub {
			color: #666;
		}

		.activity {
			color: #bf1111;
		}

		.activity,
		.sub {
			margin-top: 16rpx;
			font-size: 24rpx;
			// line-height: 36rpx;
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-line-clamp: 2;
			-webkit-box-orient: vertical;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.retentionMoney {
				color: $u-error;
				font-size: 20rpx;
				font-weight: bold;

				.text {
					padding-left: 8rpx;
				}
			}
		}

		.activity-entry {
			display: inline-block;
			padding: 4rpx 20rpx;
			margin: 10rpx 0 24rpx 0;
			font-size: 24rpx;
			color: #bf1111;
			border: 1rpx solid rgb(229, 203, 203);
			border-radius: 40rpx;
		}
	}

	.bottom-menu {
		position: fixed;
		bottom: 0;
		width: 750rpx;
		height: calc(100rpx + env(safe-area-inset-bottom));
		padding-bottom: env(safe-area-inset-bottom);
		display: flex;
		background-color: #fff;
		justify-content: space-between;

		.btns {
			display: flex;
			font-size: 22rpx;

			.btn {
				width: 100rpx;
				height: 100rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;

				&:active {
					background-color: #f2f3f4;
				}

				.contact {
					position: absolute;
					width: 100rpx;
					height: 100rpx;
					z-index: 1;
					opacity: 0;
				}
			}
		}

		.next {
			padding: 10rpx;
			display: flex;
			width: 450rpx;
			justify-content: flex-end;

			view {
				width: 50%;
				text-align: center;
				line-height: 80rpx;
				color: #fff;

				&:active {
					opacity: 0.8;
				}
			}

			view:first-child {
				background: linear-gradient(90deg, #ffd01e, #ff8917);
				border-radius: 40rpx 0 0 40rpx;
				position: relative;

				.btn {
					position: absolute;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					opacity: 0;
				}
			}

			view:last-child {
				background: linear-gradient(90deg, #64d968, #39c03e);
				border-radius: 0 40rpx 40rpx 0;
			}

			.one {
				background: linear-gradient(90deg, #ffd01e, #ff8917) !important;
				border-radius: 40rpx !important;
			}
		}
	}

	.reportFile {
		margin-left: auto;
		width: 300rpx;
		flex-wrap: wrap;
		align-items: center;
		display: flex;
		justify-content: flex-end;
	}

	.mapicon {
		width: 0;
		flex: 1;
		display: flex;

		justify-content: flex-end;

		.iconbox {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			color: #909193;
			font-size: 24rpx;

			.icon {
				width: 44rpx;
				height: 44rpx;
				border-radius: 50%;
				border: 1rpx solid #909193;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 8rpx;
			}
		}
	}
</style>